/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.support.convert;

import java.lang.reflect.Field;
import javax.persistence.AttributeConverter;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;

/**
 * 内部实现无转换函数的枚举类型的转换
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
public class EnumConverter implements AttributeConverter<Object, Object> {

  private Class<Enum> type;
  private EnumType enumType;

  public EnumConverter(Field field) {
    this.type = (Class<Enum>) field.getType();
    Enumerated enumerated = field.getAnnotation(Enumerated.class);
    if (enumerated != null) {
      this.enumType = enumerated.value();
    }
  }

  @Override
  public Object convertToDatabaseColumn(Object value) {
    if (value instanceof Enum) {
      return (enumType == null || enumType == EnumType.ORDINAL)
          ? ((Enum) value).ordinal()
          : ((Enum) value).name();
    }

    return value;
  }

  private EnumType getEnumType(Object value) {
    // 若没有指定类型需要更具数据猜一下类型
    return enumType != null
        ? enumType
        : (value instanceof Integer ? EnumType.ORDINAL : EnumType.STRING);
  }

  @Override
  public Object convertToEntityAttribute(Object value) {
    if (value != null) {
      EnumType enumType = getEnumType(value);
      if (enumType == EnumType.STRING) {
        return Enum.valueOf(type, value.toString());
      } else {
        Object[] values = type.getEnumConstants();
        int ordinal = Integer.parseInt(value.toString());
        return values[ordinal];
      }
    }

    return null;
  }
}
